using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CMS.api.Data;
using CMS.api.Repository;
using CMS.api.Utils;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using CMS.api.Fliters;
using CMS.api.Model;
using System.IO;
using Microsoft.Extensions.FileProviders;
using Microsoft.AspNetCore.HttpOverrides;

namespace CMS.api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        private string allowCors = "AllowCors";

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {


            // 注册数据库上下文到容器
            // services.AddDbContext<CMSDb>(o => o.UseNpgsql(Configuration.GetConnectionString("PostgreSql")));
            services.AddDbContext<CMSDb>(o => o.UseSqlServer(Configuration.GetConnectionString("SqlServer")));

            services.Configure<PictureOptions>(Configuration.GetSection("PictureOptions"));
            // 注册对数据库的基本操作服务到容器
            services.AddScoped(typeof(ICURDable<>), typeof(EfCURD<>));

            // 添加授权的验证服务
            services
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(option =>
                {
                    // 是否要求使用https
                    option.RequireHttpsMetadata = false;
                    // 是否保存token
                    option.SaveToken = true;

                    // 使用配置中间件，获得token的配置
                    var tokenParameter = Configuration.GetSection("TokenParameter").Get<TokenParameter>();

                    option.TokenValidationParameters =
                        new TokenValidationParameters
                        {
                            ValidateIssuer = true,  // 要不要验证发行token的人（个人或者组织）
                            ValidateAudience = false, // 是否验证受众
                            // ValidateLifetime = true,
                            ValidateIssuerSigningKey = true,  //要不要验证生成token的密钥
                            ValidIssuer = tokenParameter.Issuer,
                            // ValidAudience = "user",
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenParameter.Secret))
                        };

                });

            //添加cors 服务 配置跨域处理
            services.AddCors(x =>
                {
                    x.AddPolicy(allowCors, builder =>
                         {
                             builder
                                 .AllowAnyOrigin() //允许任何来源的主机访问
                                 .AllowAnyMethod()
                                 .AllowAnyHeader();
                             // .AllowCredentials(); //指定处理cookie
                         });
                });

            services.AddControllers(options =>
            {
                options.Filters.Add(typeof(AuditLogActionFilter));
            });

            services
                .AddSwaggerGen(c =>
                {
                    c
                        .SwaggerDoc("v1",
                        new OpenApiInfo
                        {
                            Title = "CMS.api",
                            Version = "v1"
                        });
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app
                    .UseSwaggerUI(c =>
                        c
                            .SwaggerEndpoint("/swagger/v1/swagger.json",
                            "CMS.api v1"));
            }

            // app.UseStaticFiles();

            #region 
            string filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"UploadFiles/Images");
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), @"UploadFiles/Images")),
                RequestPath = new Microsoft.AspNetCore.Http.PathString("/UploadFiles/Images")
            }
            );
            #endregion



            // 由于请求通过反向代理转发，因此使用 Microsoft.AspNetCore.HttpOverrides 包中的转接头中间件。
            // 此中间件使用 X-Forwarded-Proto 标头来更新 Request.Scheme，使重定向 URI 和其他安全策略能够正常工作。
            // 简单来说，使用nginx的反向代理，需要使用这个中间件（好吧，通过实际测试，没有的情况下，token是没有问题的，其它情况未测试）
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseRouting();



            // 使用允许跨域请求
            app.UseCors(allowCors);

            // 登录验证
            app.UseAuthentication();
            // 授权
            app.UseAuthorization();


            app
                .UseEndpoints(endpoints =>
                {
                    // 配置服务实现
                    endpoints.MapControllers();
                });
        }
    }
}
